<?php
namespace app\backstage\logic;
use think\Db;

class Order
{
    /*列表数据获取*/
    public function getList($params)
    {
        $field = 'o.id,o.uid,o.quick_id,o.agent_id,o.channel_id,o.ip_addr,o.recharge_type,o.recharge_activity_id,o.user_reg_date,o.out_trade_no,o.trade_no,o.total_fee,';
        $field .= 'o.status,o.pay_time,o.type,o.vipdays,o.virtual_currency,o.pay_type,o.recharge_times,o.nid,o.link_id,o.phone_model,o.advert_media_id,o.is_report,';
        $field .= 'o.create_time,o.update_time,o.is_refund';

        if (request()->_role->alias == 'agent') {
            $params['agent_id'] = request()->_user->id;
        }
        if (request()->_role->alias == 'channel') {
            $params['channel_id'] = request()->_user->id;
        }
        if( request()->_role->alias == 'eb')
        {
            $agent_ids = Db::table('cms_manager_user')->where('parent_id', '=', request()->_user->id)
                ->column('id');
            $params['agent_id'] = $agent_ids ? $agent_ids : [0];
        }

        if (isset($params['status']) && $params['status'] == 4) {
            $params['is_refund'] = 1;
            unset($params['status']);
        }

        $condition[] = ['o.quick_id', 'eq', 'require', 'quick_id'];
        $condition[] = ['o.agent_id', 'in', 'not_empty', 'agent_id'];
        $condition[] = ['o.out_trade_no', 'eq', 'require', 'order_no'];
        $condition[] = ['o.trade_no', 'eq', 'require', 'transaction_no'];
        $condition[] = ['o.channel_id', 'eq', 'require', 'channel_id'];
        $condition[] = ['o.quick_id', 'eq', 'gt:0', 'quick_id'];
        $condition[] = ['o.uid', 'eq', 'gt:0', 'uid'];
        $condition[] = ['o.status', 'eq', 'gt:0', 'status'];
        $condition[] = ['pay_type', 'eq', 'require', 'pay_type'];
        $condition[] = ['link_id', 'eq', 'require', 'link_id'];
        $condition[] = ['nid', 'eq', 'require', 'nid'];
        $condition[] = ['recharge_activity_id', 'eq', 'require', 'recharge_activity_id'];
        $condition[] = ['oa.advertiser_id', 'eq', 'gt:0', 'advertiser_id'];
        $condition[] = ['oa.campaign_id', 'eq', 'gt:0', 'campaign_id'];
        $condition[] = ['oa.aid', 'eq', 'gt:0', 'aid'];
        $condition[] = ['oa.cid', 'eq', 'gt:0', 'cid'];
        $condition[] = ['o.user_reg_date', 'eq', 'require', 'user_reg_date'];
        $condition[] = ['o.user_source_date', 'eq', 'require', 'user_source_date'];
        $condition[] = ['o.recharge_times', 'eq', 'gt:0', 'recharge_times'];
        $condition[] = ['o.is_refund', 'eq', 'gt:0', 'is_refund'];

        $where = buildQueryCondition($condition, $params);

        if (isset($params['start_date']) && strlen($params['start_date']) > 1) {
            $where[] = ['o.create_time', '>=', $params['start_date'] . ' 00:00:00'];
        }

        if (isset($params['end_date']) && strlen($params['end_date']) > 1) {
            $where[] = ['o.create_time', '<=', $params['end_date'] . ' 23:59:59'];
        }
        /*if (isset($params['first']) && $params['first'] == 1) {
            $where[] = ['o.recharge_times', '<=', 1];
        } elseif (isset($params['first']) && $params['first'] == 2) {
            $where[] = ['o.recharge_times', '>', 1];
        }*/

        if (isset($params['field'])) {
            $orderBy = ['o.'.$params['field'] => $params['order']];
        } else {
            $orderBy = ['o.id' => 'DESC'];
        }

        $Order = \think\facade\App::model('Order');
        $list = $Order->getList($where, $field, $params['page'], $params['limit'], $orderBy);

        if ($list) {

            $channel_id_gh = array_unique(array_column($list, 'channel_id'));
            $channels = Db::table('cms_manager_user')->where('id', 'in', $channel_id_gh)->column('id,account');

            $agent_id_gh = array_unique(array_column($list, 'agent_id'));
            $agents = Db::table('cms_manager_user')->where('id', 'in', $agent_id_gh)->column('id,account,remarks','id');


            $quick_id_gh = array_unique(array_column($list, 'quick_id'));
            $quicks = Db::table('quick_app')->where('id', 'in', $quick_id_gh)->column('id,name');

            $link_id_gh = array_unique(array_column($list, 'link_id'));
            $links = Db::table('quick_link')->where('id', 'in', $link_id_gh)->field('id,name,token')->select();
            $links = array_column($links,null,'id');

            $state = ['1' => '<span class="layui-badge">待支付</span>',
                '2' => '<span class="layui-badge layui-bg-green">已支付</span>',
                '3' => '<span class="layui-badge layui-bg-orange">已失效</span>',
                '4' => '<span class="layui-badge layui-bg-cyan">已退款</span>',
            ];

            $nid_gh = array_unique(array_column($list, 'nid'));
            $books = Db::table('novel')->where('id', 'in', $nid_gh)->column('id,title');

            $uid_gh = array_unique(array_column($list, 'uid'));
            $uInfos = Db::table('quick_user')->where('id', 'in', $uid_gh)->column('id,regtime,vip_exp_time');

            $recharge_activity_id_gh = array_unique(array_column($list,'recharge_activity_id'));
            $activitys = Db::table('pay_recharge_activity')->where('id','in',$recharge_activity_id_gh)->column('id,title');

            $order_id_gh = array_column($list, 'id');
            $reports = Db::table('pay_order_advert')->where('order_id','in',$order_id_gh)
                ->column('order_id,behavior_id,report_result,advertiser_id,aid,cid,campaign_id');

            $report_hand = Db::table('pay_order_report_hand')->where('order_id','in',$order_id_gh)
                ->column('order_id,create_time');

            foreach ($list as $k => $v) {

                $list[$k]['total_fee']      = round($v['total_fee'] / 100, 2);
                $list[$k]['state']          = $v['is_refund'] == 1 ? $state[4] : $state[$v['status']];
                $list[$k]['pay_time']       = $v['pay_time'] > 1 ? date('Y-m-d H:i:s', $v['pay_time']) : '';
                $list[$k]['pay_type']       = getPayType($v['pay_type']);
                $list[$k]['media_name']     = isset($reports[$v['id']]) && $reports[$v['id']]['behavior_id'] > 0 ? getAdvertMediaName($v['advert_media_id']) : '无';
                $list[$k]['channel_name']   = isset($channels[$v['channel_id']]) ? $channels[$v['channel_id']] : '';
                $list[$k]['agent_name']     = isset($agents[$v['agent_id']]) ? $agents[$v['agent_id']]['account'] : '';

                if (request()->_role->alias == 'admin' || request()->_role->alias == 'service') {
                    $list[$k]['agent_remark']   = isset($agents[$v['agent_id']]) ? $agents[$v['agent_id']]['remarks'] : '';
                }



                $list[$k]['quick_name']     = isset($quicks[$v['quick_id']]) ? $quicks[$v['quick_id']] : '';
                $list[$k]['recharge_info']  = $v['type'] == 1 ? "充值书币：{$v['virtual_currency']}" : "充值会员：{$v['vipdays']}天";
                $list[$k]['create_time_user'] = $uInfos[$v['uid']]['regtime'];
                $list[$k]['recharge_type_format'] = $v['recharge_type'] == 1 ? '充值订单' : '活动订单';
                $list[$k]['report_result']  = isset($reports[$v['id']]) ? $reports[$v['id']]['report_result'] : '--';
                $list[$k]['advertiser_id']  = isset($reports[$v['id']]) ? $reports[$v['id']]['advertiser_id'] : '';
                $list[$k]['aid']            = isset($reports[$v['id']]) ? $reports[$v['id']]['aid'] : '';
                $list[$k]['cid']            = isset($reports[$v['id']]) ? $reports[$v['id']]['cid'] : '';
                $list[$k]['campaign_id']    = isset($reports[$v['id']]) ? $reports[$v['id']]['campaign_id'] : '';

                if($v['recharge_type'] == 1)
                {
                    $list[$k]['source'] = isset($books[$v['nid']]) ? '小说：'.$books[$v['nid']] : '';
                }

                if($v['recharge_type'] == 2)
                {
                    $list[$k]['source'] = isset($activitys[$v['recharge_activity_id']]) ? "活动 [ID:{$v['recharge_activity_id']}]：{$activitys[$v['recharge_activity_id']]}" : '';
                }
                $list[$k]['link_source']  = '';
                if (isset($links[$v['link_id']])){
                    $list[$k]['link_source'] = " [ID:{$v['link_id']}]：" . $links[$v['link_id']]['name'];
                }

                $list[$k]['report_hand'] = isset($report_hand[$v['id']]) ? '（手动）': '';
            }
        }

        $total_price = Db::table('pay_order')->alias('o')
                        ->leftJoin('pay_order_advert oa','oa.order_id=o.id')
                        ->where($where)->sum('total_fee');

        $total_price = $total_price && $total_price > 0 ? $total_price : 0;

        $result['totalRow']['total_fee'] = round($total_price / 100, 2);
        $result['count'] = $Order->getTotalNumber($where);
        $result['list'] = $list;
        return $result;
    }

}